package com.lai.qq.admin.exception;


import com.lai.qq.admin.biz.res.RebackInfoResult;
import com.lai.qq.admin.biz.res.ResultEnums;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理 只处理controller层抛出的异常
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    private final static Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 全局异常捕捉处理
     *
     */
    /*@ExceptionHandler(Exception.class)
    @ResponseBody
    public  RebackInfoResult handle(Exception e) {
        logger.error("发生未处理的异常={}", e.getMessage(), e);
        RebackInfoResult result = new RebackInfoResult();
        return  result.systemError();
    }*/

    /**
     * 自定义异常处理  参数校验
     *
     */
    /*@ExceptionHandler(value = MethodArgumentNotValidException.class)
    public  Result MethodArgumentNotValidHandler(HttpServletRequest request,
                                                       MethodArgumentNotValidException e) {
        FieldError error = e.getBindingResult().getFieldErrors().get(0);
        logger.error("参数校验失败={}", error.getDefaultMessage(), e);
        return Result.paramError(error);
    }*/


   /* @ExceptionHandler(MethodArgumentNotValidException.class)
    public RebackInfoResult MethodArgumentNotValidHandler(MethodArgumentNotValidException ex) {
        FieldError fieldError = ex.getBindingResult().getFieldError();
        log.info("参数校验异常:{}({})", fieldError.getDefaultMessage(),fieldError.getField());
        RebackInfoResult result = new RebackInfoResult();
        result.setCode(ResultEnums.PARAM_ERROR.getCode());
        result.setMsg(ResultEnums.PARAM_ERROR.getMsg());
        result.setData(fieldError.getDefaultMessage());
        return result;
    }*/

    @ExceptionHandler(BindException.class)
    public RebackInfoResult handleBindException(BindException ex) {
        //校验 除了 requestbody 注解方式的参数校验 对应的 bindingresult 为 BeanPropertyBindingResult
        FieldError fieldError = ex.getBindingResult().getFieldError();
        log.info("必填校验异常:{}({})", fieldError.getDefaultMessage(),fieldError.getField());
        RebackInfoResult result = new RebackInfoResult();
        result.setCode(ResultEnums.PARAM_ERROR.getCode());
        result.setMsg(ResultEnums.PARAM_ERROR.getMsg());
        result.setData(fieldError.getDefaultMessage());
        return result;
    }


}